import request from './index';

// ================== 类型定义 (v2.0) ==================

/**
 * 字幕文件 (隸屬於 Project)
 */
export interface SubtitleFile {
  subtitle_id: number;
  project_uid: string;
  language: string;
  status: 'generating' | 'generated' | 'uploading' | 'completed' | 'failed' | 'cancelled';
  file_path: string | null;
  created_at: string;
  updated_at: string;
}

/**
 * 项目 (核心模型)
 */
export interface Project {
  project_uid: string;
  episode_id: string;
  original_video_path: string | null;
  status: 'pending' | 'processing' | 'completed_generation' | 'partial_failure' | 'completed' | 'failed' | 'cancelled';
  status_message: string | null;
  error_message: string | null;
  created_at: string;
  updated_at: string;
  subtitles: SubtitleFile[];
}

/**
 * 项目分页响应
 */
export interface ProjectPage {
  total: number;
  items: Project[];
}

/**
 * 获取项目列表的查询参数
 */
export interface GetProjectsParams {
  skip?: number;
  limit?: number;
  status?: string | string[];
  episode_id?: string;
  q?: string;
  language?: string;
  created_from?: string;
  created_to?: string;
  sort_by?: string;
  order?: 'asc' | 'desc';
}

// ================== API 函数 (v2.0) ==================

/**
 * 1. 创建新项目
 * @param formData 包含 episode_id, languages, และ video 或 video_url
 */
export function createProject(formData: FormData): Promise<Project> {
  return request.post<Project, Project>('/taskapi/projects', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
}

/**
 * 1.1 批量创建项目
 * @param projects 项目数组，每个项目包含 episode_id, languages, video_url 等
 */
export interface BatchCreateProjectItem {
  episode_id: string;
  video_url?: string;
  languages: string[];
}

export interface BatchCreateProjectsResponse {
  success_count: number;
  failure_count: number;
  created_projects: Project[];
  errors: Array<{
    episode_id: string;
    error: string;
  }>;
}

export function batchCreateProjects(projects: BatchCreateProjectItem[]): Promise<BatchCreateProjectsResponse> {
  return request.post<BatchCreateProjectsResponse, BatchCreateProjectsResponse>('/taskapi/projects/batch-create', {
    projects
  });
}

/**
 * 2. 获取项目列表 (分页/筛选/排序)
 * @param params 查询参数
 */
export function getProjects(params: GetProjectsParams): Promise<ProjectPage> {
  // The backend might not handle array params correctly if not stringified.
  // We will pass them as is, but if issues arise, this is a place to check.
  return request.get<ProjectPage, ProjectPage>('/taskapi/projects', { params });
}

/**
 * 3. 获取单个项目详情
 * @param projectUid 项目的唯一ID
 */
export function getProject(projectUid: string): Promise<Project> {
  return request.get<Project, Project>(`/taskapi/projects/${projectUid}`);
}

/**
 * 4. 删除项目
 * @param projectUid 项目的唯一ID
 */
export function deleteProject(projectUid: string): Promise<{ message: string }> {
  return request.delete<{ message: string }, { message: string }>(`/taskapi/projects/${projectUid}`);
}

/**
 * 5. 取消项目
 * @param projectUid 项目的唯一ID
 */
export function cancelProject(projectUid: string): Promise<Project> {
  return request.post<Project, Project>(`/taskapi/projects/${projectUid}/cancel`);
}

/**
 * 6. 重试项目
 * @param projectUid 项目的唯一ID
 */
export function retryProject(projectUid: string): Promise<Project> {
  return request.post<Project, Project>(`/taskapi/projects/${projectUid}/retry`);
}

/**
 * 7. 批量操作项目
 */
export type ProjectBatchAction = 'retry' | 'cancel' | 'delete';
interface BatchUpdateProjectsPayload {
    action: ProjectBatchAction;
    project_uids: string[];
}
export function batchUpdateProjects(action: ProjectBatchAction, project_uids: string[]): Promise<any> {
    const payload: BatchUpdateProjectsPayload = { action, project_uids };
    return request.post('/taskapi/projects/batch', payload);
}

/**
 * 8. 按状态批量删除项目
 * @param status 目标状态
 */
export function batchDeleteProjectsByStatus(status: Project['status']): Promise<any> {
    return request.post('/taskapi/projects/batch-delete-by-status', { status });
}

/**
 * 9. 手动为字幕文件触发上传
 * @param subtitleId 字幕文件的ID
 */
export function resubmitSubtitleUpload(subtitleId: number): Promise<any> {
    return request.post(`/taskapi/subtitles/${subtitleId}/submit`);
} 